node에서 Redis 사용하기

Redis를 node에서 사용해보자.

node에서 redis 사용

redis 공식문서-nodejs
node의 redis 모듈을 사용할 수 있다.
redis 모듈은 레디스의 커맨드를 모두 지원한다.

설치

npm install redis

연결

import { createClient } from 'redis';

const client = createClient();
//host에 연결하는 경우
const clinet = createClient({
  url: 'redis://alice:foobared@awesome.redis.server:6380'
});

client.on('error', err => console.log('Redis Client Error', err));

await client.connect();

set, get

간단하게 key value값을 설정할 수 있다

await client.set('key', 'value');
const value = await client.get('key');

CRUD 구현

// GET
router.get('/', async (req, res, next) => {
   await redisCli.get('username');
});

// POST
router.post('/set', async (req, res, next) => {
   await redisCli.set('username', 'inpa');
});

// DELETE
router.delete('/del', async (req, res, next) => {
   // exist : 키가 존재하는지
   const n = await redisCli.exists('username'); // true: 1 , false: 0
   if(n) await redisCli.del('username');
});

// PUT
router.put('/rename', async(req, res, next) => {
   // username이라는 키값이 있다면 그 값을 helloname으로 바꿈
   redisCli.rename('username', 'helloname');
});

redis 자료형과 get set

redis의 value에는 다양한 자료형이 있다.
각 자료형에 따른 별도의 get, set 메서드가 있다.

// String
await redisCli.set('name', 'nyong')
await redisCli.get('name') // nyong

// List
await redisCli.rpush('fruits', 'apple', 'orange', 'pineapple')
await redisCli.lpush('fruits', 'banana', 'pear')
await redisCli.lrange('fruits', 0, -1) // ['pear', 'banana', 'apple', 'orange', 'apple']
// 0 과 -1은 시작과 끝 인덱스를 의미

// Hash
await redisCli.hmset('friends', 'name', 'nyong', 'age', 30)
await redisCli.hgetall('friends') // { name : 'nyong', age : 30 }

// Set
await redisCli.sadd('fruits', 'apple', 'orange', 'pear', 'banana', 'apple')
await redisCli.smembers('fruits') // ['banana', 'apple', 'orange', 'pear'] // apple은 2개여서 중복제거

// Sorted Set
await redisCli.zadd('fruits', 1, 'apple', 5, 'orange', 3, 'pear', 4, 'banana', 8, 'grape')
await redisCli.zrange('fruits', 0, -1) // ['apple', 'pear', 'banana', 'orange', 'grape']

events

on 메서드로 이벤트를 등록할 수 있다.
사용할 수 있는 이벤트는 다음과 같다.

redisCli.on('connect', () => {
  console.info('Redis connected!');
});
redisCli.on('error', (err) => {
  console.error('Redis Client Error', err);
});

트랜잭션

.multi() 메서드 이후에 다른 메서드들을 체이닝으로 연결하면 트랜잭션이 구성된다.
트랜잭션이 완료되면 .exec() 호출해서 결과 배열을 받게 된다.

await redisCli.set('another-key', 'another-value');

const [setKeyReply, otherKeyValue] = await redisCli
  .multi()
  .set('key', 'value')
  .get('another-key')
  .exec(); // ['OK', 'another-value']

node에서 redis를 session storage로 사용하기

redis를 session storage로 사용해보자

redis와 connect-redis를 설치한다.

npm install redis connect-redis

redis는 클라이언트를 생성하기 위해서, connect-redis는 세션을 레디스에 저장하기 위해 사용.

session의 store 옵션을 redisStore로 설정해주면 메모리가 아닌 redis에 세션을 유지한다.

const redis = require("redis");
const RedisStore = require("connect-redis").default;
...
const redisClient = redis.createClient({
  host: process.env.REDIS_HOST_DEV,
  port: process.env.REDIS_PORT_DEV,
  password: process.env.REDIS_PASSWORD_DEV,
});

redisClient.on("connect", () => {
  logger.info("Redis connection success");
});
(async () => {
  await redisClient.connect();
})();
...
app.use(
  session({
    secret: process.env.COOKIE_SECRET,
    resave: false,
    saveUninitialized: false,
    store: new RedisStore({
      client: redisClient,
    }),
  })
);

redis에서 생서된 session을 확인할 수 있다.
Attachments/Picture/Pasted image 20240108134304.png|300

reference